package com.zhihu.service.impl;

import com.zhenzi.sms.ZhenziSmsClient;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.service.MessageService;
import com.zhihu.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * @author : zhangzheng
 * ClassName: MessageService
 * @date : 2021/9/3 16:26
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisUtils redisUtils;
    /**
     * 短信验证
     * @param telephone
     * @return
     */
    @Override
    public BaseResult sendMsg(String telephone) {
        //生成一个随机验证码
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<6;i++){
            stringBuffer.append(random.nextInt(10));
        }
        String apiUrl = "https://sms_developer.zhenzikj.com";
        String appId = "109745";
        String appSecret = "c710b79e-9c75-45bb-902e-baee78e037dc";
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);

        try {
            //给用户发一份验证码
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", telephone);
            params.put("templateId", "6363");
            String[] templateParams = new String[2];
            //System.out.println(templateParams);
            templateParams[0] = stringBuffer.toString();//随机验证码
            templateParams[1] = "10分钟";
            //System.out.println(templateParams[0]+templateParams[1]);
           params.put("templateParams", templateParams);
            //System.out.println(params);
            String result = client.send(params);
            //System.out.println(result);
            //发送成功向缓存中放一份验证码
            redisUtils.set(telephone,templateParams[0]);
            //设置10分钟过期时间
            redisUtils.expire(telephone,600);
        } catch (Exception e) {
            //异常
            System.out.println(e.getMessage());
        }
        return new BaseResult(0,"发送成功!");
    }
}
